package com.maotouying.owlsmart.LoginPage;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.maotouying.owlsmart.R;
import com.maotouying.owlsmart.SmartUtil.md5.MD5Util;
import com.maotouying.owlsmart.SmartUtil.md5.md5Encrypt;
import com.maotouying.owlsmart.SmartUtil.Http.portPath;
import com.maotouying.owlsmart.SmartUtil.SystemUtil;

import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.UUID;
import java.util.regex.Pattern;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class SigninActivity extends AppCompatActivity {


    //注册页面
    private TextView go_login;
    private EditText edt_username,edt_password1,edt_password2,edt_email,edt_phone;
    private Button btn_signin;
    private String registerPath = "/owl/user/register.do";
    private String smartPath;
    private md5Encrypt md5;
    private ImageView iv_back;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_signin);
        SystemUtil.setStatusBarColor(this, this.getResources().getColor(R.color.top_background_color));


        //拿到Address根地址
        portPath port = new portPath();
        smartPath = port.getPath(SigninActivity.this);

        edt_username = (EditText)findViewById(R.id.edt_username);
        edt_password1 = (EditText)findViewById(R.id.edt_password1);
        edt_password2 = (EditText)findViewById(R.id.edt_password2);
        edt_email = (EditText)findViewById(R.id.edt_email);
        edt_phone = (EditText)findViewById(R.id.edt_phone);

        btn_signin= (Button) findViewById(R.id.btn_signin);
        go_login = (TextView)findViewById(R.id.go_login);

        iv_back= (ImageView) findViewById(R.id.iv_back);



        edt_username.setImeOptions(EditorInfo.IME_FLAG_NAVIGATE_NEXT);
        edt_username.setSingleLine();
        edt_password1.setImeOptions(EditorInfo.IME_FLAG_NAVIGATE_NEXT);
        edt_password1.setSingleLine();
        edt_password2.setImeOptions(EditorInfo.IME_FLAG_NAVIGATE_NEXT);
        edt_password2.setSingleLine();
        edt_email.setImeOptions(EditorInfo.IME_FLAG_NAVIGATE_NEXT);
        edt_email.setSingleLine();
        edt_phone.setImeOptions(EditorInfo.IME_FLAG_NAVIGATE_NEXT);
        edt_phone.setSingleLine();


        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        go_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(SigninActivity.this, LoginActivity.class);
                startActivity(intent);
            }
        });

        Signin();

    }

    private void Signin(){
        btn_signin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //先判断各个字段是否为空
                String usename = edt_username.getText().toString();
                String password1 = edt_password1.getText().toString();
                String password2 = edt_password2.getText().toString();
                String email = edt_email.getText().toString();
                String phone = edt_phone.getText().toString();

                boolean state_email,state_username,state_password2,state_phone,state_password1;

                if(!email.contains("@")|!email.contains(".com")){
                    edt_email.setText("");
                    edt_email.setHint("邮箱格式不正确");
                    state_email = false;
                }else {
                    state_email =true;
                }
                if(usename.length()<=3){
                    edt_username.setText("");
                    edt_username.setHint("请输入3位以上的昵称");
                    state_username = false;
                }else {
                    state_username =true;
                }
                if(!password1.contains(password2)){
                    edt_password2.setText("");
                    edt_password2.setHint("两次输入的密码不统一");
                    state_password2 = false;
                }else {
                    state_password2 =true;
                }
                if(phone.length()!=11&isInteger(phone)){
                    edt_phone.setText("");
                    edt_phone.setHint("手机号码格式不正确");
                    state_phone = false;
                }
                else {
                    state_phone =true;
                }
                if(password1.equals("")&password1.equals("")){
                    edt_password1.setText("");
                    edt_password2.setText("");
                    edt_password1.setHint("密码不可以为空");
                    edt_password2.setHint("密码不可以为空");
                    state_password1 = false;
                }else {
                    state_password1 =true;
                }

                if(state_email& state_username &state_password2&state_phone&state_password1){


                    postTest(usename,password1,email,phone);
                }


            }
        });



    }

    public static boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }



    public void postTest(final String usename,final String password1,String email,String phone){

        md5 = new md5Encrypt();
        OkHttpClient client = new OkHttpClient();
        //post请求
        FormBody formBody = new FormBody.Builder()
               // .add("owlId",getUniquePsuedoID())
                .add("username",usename)
                .add("password",md5.toMd5(password1))
                .add("email",email)
                .add("phone",phone)
                .build();

        Request request = new Request.Builder().url(smartPath+registerPath)
                .post(formBody).build();

        client.newCall(request).enqueue(new Callback() {
            public void onFailure(Call call, IOException e) {
                System.out.println(e.getMessage());
            }

            public void onResponse(Call call, Response response) throws IOException {
                if(response.code() >= 200 && response.code() < 300) {
                    String result = response.body().string();
                    System.out.println(result);

                    JSONObject code = JSONObject.parseObject(result);
                    int status = code.getInteger("status");
                    if(status==0){

                        Intent intent = new Intent(SigninActivity.this, LoginActivity.class);
                        intent.putExtra("activity","SigninActivity");
                        intent.putExtra("email",email);
                        intent.putExtra("password",password1);
                        startActivity(intent);
                        finish();
                    }else {
                        String msgHint = code.getString("msg");//拿到data数据
                        //System.out.println("msg:::"+msg);演示一把

                        Message msg = new Message();
                        msg.what = 16;
                        Bundle bundle = new Bundle();
                        bundle.putString("msgHint", msgHint);//往Bundle中存放数据
                        msg.setData(bundle);
                        Thandler.sendMessage(msg);

                    }
                }
            }
        });
    }


    private Handler Thandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 16:
                    String msgHint = msg.getData().getString("msgHint");//接受msg传递过来的参数
                    System.out.println("Handler::::"+msgHint);
                    //这里操作更新ui

                    Toast.makeText(SigninActivity.this, msgHint, Toast.LENGTH_LONG).show();
                    break;
            }
        }
    };


    //获得独一五二的信息
    public String getUniquePsuedoID() {
        String serial = null;

        String m_szDevIDShort = "35" +
                Build.BOARD.length() % 10 + Build.BRAND.length() % 10 +

                Build.CPU_ABI.length() % 10 + Build.DEVICE.length() % 10 +

                Build.DISPLAY.length() % 10 + Build.HOST.length() % 10 +

                Build.ID.length() % 10 + Build.MANUFACTURER.length() % 10 +

                Build.MODEL.length() % 10 + Build.PRODUCT.length() % 10 +

                Build.TAGS.length() % 10 + Build.TYPE.length() % 10 +

                Build.USER.length() % 10; //13 位

        try {
            serial = Build.class.getField("SERIAL").get(null).toString();
            //API>=9 使用serial号
            return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
        } catch (Exception exception) {
            //serial需要一个初始化
            serial = "serial"; // 随便一个初始化
        }
        //使用硬件信息拼凑出来的15位号码
        return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();

    }

    public String getIPAddress(Context context) {
        NetworkInfo info = ((ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        if (info != null && info.isConnected()) {
            if (info.getType() == ConnectivityManager.TYPE_MOBILE) {//当前使用2G/3G/4G网络
                try {
                    //Enumeration<NetworkInterface> en=NetworkInterface.getNetworkInterfaces();
                    for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                        NetworkInterface intf = en.nextElement();
                        for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                            InetAddress inetAddress = enumIpAddr.nextElement();
                            if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                                return inetAddress.getHostAddress();
                            }
                        }
                    }
                } catch (SocketException e) {
                    e.printStackTrace();
                }


            } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {//当前使用无线网络
                WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());//得到IPV4地址
                return ipAddress;
            }
        } else {
//当前无网络连接,请在设置中打开网络
        }
        return null;
    }


    /**
     *      * 将得到的int类型的IP转换为String类型
     *      *
     *      * @param ip
     *      * @return
     *      
     */
    public static String intIP2StringIP(int ip) {
        return (ip & 0xFF) + "." +
                ((ip >> 8) & 0xFF) + "." +
                ((ip >> 16) & 0xFF) + "." +
                (ip >> 24 & 0xFF);
    }

}